import * as  mongoHelper from './service/mongoHelper'
import * as apiHelper from './service/apiHelper'
import InspectRecord from './model/InspectRecord'
import * as fs from 'fs';
import * as imageUploader from './service/imageUploader'

const lineNameList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 17].map((x) => `${x}号线`)
const SEPERATOR = "～";

async function runAsync() {
    let { client, db } = await mongoHelper.openMongoAsync()
    for (const lineName of lineNameList) {
        console.log(`start process ${lineName}`);
        //先从顺凯那里拉数据
        let line = await apiHelper.fetchLineFromRemoteAsync(lineName)
        //开始进行比对
        for (let section of line.sections) {
            let sectionName = `${section.metroStationNameStart}${SEPERATOR}${section.metroStationNameEnd}`
            let sectItem = await apiHelper.getSectionAsync(sectionName);//我们自己数据库对该section的定义

            if (!sectItem) continue;
            for (let prj of section.projects) {
                let syncRecord = { name: prj.name, date: prj.projTaskLastedResultDate, section: sectionName, sectionName };
                let isSynced = await mongoHelper.isRecordSyncAlready(db, syncRecord);//是否同步过
                if (isSynced) {
                    console.log(`continue : ${JSON.stringify(syncRecord)}  已经同步过，不处理`);
                    continue;//同步过就不处理了
                }
                let tobeUpdateRecord = InspectRecord.parseFromSkyFormat(prj, sectItem)//转换一下数据格式，大家字段定义都各不相同
                tobeUpdateRecord.imageList = await imageUploader.copyImagesFromSkyToQiniu(tobeUpdateRecord.imageList);//转存图片到七牛去
                // fs.writeFileSync('./temp.txt', JSON.stringify(tobeUpdateRecord) + '\r\n', { flag: 'a' }) /** @todo 即将被删除 */
                await apiHelper.uploadToMetroProjects(tobeUpdateRecord);//存我们自己数库
                await mongoHelper.saveSyncRecord(db, syncRecord)//存入同步中
            }
        }
        await mongoHelper.updateLineAysnc(db, lineName, line)
        console.log(`finish ${lineName}`);
    }
    await mongoHelper.closeMongoAsync(client)
    console.log('all finish');
}



let timeout = null;

function start(hour: number = 24) {
    runAsync()
    timeout = setTimeout(() => {
        start(hour);
    }, hour * 3600 * 1000);//一天运行一次
}

function stop() {
    if (!timeout) return;
    clearTimeout(timeout)
}

export { start, stop, runAsync }
